//
//  MAVipViewController.m
//  MateAdv
//
//  Created by 茶 on 2023/9/14.
//

#import "MAVipViewController.h"
#import "MAVipMealModel.h"
#import "MAVipView.h"
#import "MAIAPTool.h"
#import "MAUserModel.h"

@interface MAVipViewController ()

@property (nonatomic, strong) MAVipView *vipView;
@property (nonatomic, strong) MAVipMealModel *model;
@property (nonatomic, strong) NSMutableArray <MAMealItemModel *>*itemArray;

@end

@implementation MAVipViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = MAColor(@"#FF0071");
    [self initDatasource];

}

- (void)initDatasource {
    NSDictionary *savedMeal = [kUserDefaults objectForKey:kSavedMeal];
    if (savedMeal) {
        self.model = [MAVipMealModel yy_modelWithJSON:savedMeal];
        [self initInterface];
    } else {
        [SVProgressHUD show];
        MAWeakify(self);
        [ReqManager fetchMealSuccessed:^(id _Nonnull object) {
            MAStrongify(self);
            [SVProgressHUD dismiss];
            NSDictionary *savedMeal = [kUserDefaults objectForKey:kSavedMeal];
            self.model = [MAVipMealModel yy_modelWithJSON:savedMeal];
            [self initInterface];
        } failed:^(NSError * _Nonnull error) {
            MAStrongify(self);
            [SVProgressHUD dismiss];
            [self.view makeToast:@"套餐获取失败，请检查网络"];
        }];
    }
}

- (void)initInterface {
    [self.view addSubview:self.vipView];
    [_vipView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    MAWeakify(self);
    _vipView.confirmBlock = ^(NSUInteger index) {
        MAStrongify(self);
        [self confirmEventWithIndex:index];
    };
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"恢复购买" style:UIBarButtonItemStylePlain target:self action:@selector(resumeEvent)];
    self.navigationItem.rightBarButtonItem = rightItem;
    self.navigationController.navigationBar.tintColor = UIColorWhite;
}

- (void)resumeEvent {
    if (kUserModel.vipStatus> 0) {
        [self.view makeToast:@"您已经是VIP,无需恢复购买"];
    } else {
        [SVProgressHUD show];
        MAWeakify(self);
        [ReqManager fetchUserInfoWithSuccessed:^(id  _Nonnull object) {
            if ([object containKey:@"user_info"]) {
                [kUserDefaults setObject:object[@"user_info"] forKey:kUserInfo];
            }
        } failed:nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            MAStrongify(self);
            [SVProgressHUD dismiss];
            [self.view makeToast:@"恢复成功"];
        });
    }
}

- (void)confirmEventWithIndex:(NSUInteger)index {
    MAWeakify(self);
    MAMealItemModel *model = self.itemArray[index];
    [ReqManager createOrderWithParams:@{@"data_id" : model.identifier, @"type" : model.type, @"pay_type" : model.payType} successed:^(id  _Nonnull object) {
        [kUserDefaults setObject:object[@"pay_order_no"] forKey:kPayOrderNo];
        [[MAIAPTool shareTool] ma_buyProductWithId:model.appleProductId completion:^(BOOL succed, NSString * _Nonnull msg) {
            if(succed){
                [SVProgressHUD dismiss];
                [ReqManager fetchUserInfoWithSuccessed:^(id  _Nonnull object) {
                    if ([object containKey:@"user_info"]) {
                        [kUserDefaults setObject:object[@"user_info"] forKey:kUserInfo];
                    }
                } failed:nil];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                MAStrongify(self);
                [SVProgressHUD dismiss];;
                [self.view makeToast:msg];
                if (succed) {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.navigationController popViewControllerAnimated:YES];
                    });
                }
            });
        }];
    } failed:^(NSError * _Nonnull error) {
        MAStrongify(self);
        [self.view makeToast:error.localizedDescription];
    }];
    
}

- (MAVipView *)vipView {
    if (_vipView) return _vipView;
    _vipView = [MAVipView new];
    _itemArray = [NSMutableArray arrayWithCapacity:self.model.item.count];
    for (MAMealItemModel *model in self.model.item) {
        if (model.payType.integerValue == 3) {
            [_itemArray addObject:model];
        }
    }
    _vipView.items = _itemArray;
    return _vipView;;
}
@end
